package com.dkd.manage.service.impl;

import com.dkd.common.core.domain.TreeSelect;
import com.dkd.common.utils.DateUtils;
import com.dkd.manage.domain.Region;
import com.dkd.manage.domain.vo.RegionVo;
import com.dkd.manage.mapper.EmpMapper;
import com.dkd.manage.mapper.RegionMapper;
import com.dkd.manage.service.IRegionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 区域管理Service业务层处理
 * 
 * @author daitingwei
 * @date 2025-07-28
 */
@Service
public class RegionServiceImpl implements IRegionService 
{
    @Resource
    private EmpMapper empMapper;
    @Resource
    private RegionMapper regionMapper;

    /**
     * 获取所有区域统计信息
     * 
     * @return 所有区域统计信息（总区域数、总节点数、总设备数、活跃设备数）
     */
    @Override
    public Map<String, Integer> getAllStatistics() {
        Map<String, Integer> statistics = new HashMap<>();
        // 获取所有区域总数
        Integer totalRegions = regionMapper.selectTotalRegionCount();
        // 获取所有节点总数
        Integer totalNodes = regionMapper.selectTotalNodeCount();
        // 获取所有设备总数（这里暂时用节点数代替，实际应根据设备表统计）
        Integer totalDevices = regionMapper.selectTotalDeviceCount();
        // 获取活跃设备数（这里暂时用节点数的80%代替，实际应根据设备在线状态统计）
        Integer activeDevices = totalDevices != null ? (int)Math.round(totalDevices * 0.8) : 0;
        
        statistics.put("totalRegions", totalRegions != null ? totalRegions : 0);
        statistics.put("totalNodes", totalNodes != null ? totalNodes : 0);
        statistics.put("totalDevices", totalDevices != null ? totalDevices : 0);
        statistics.put("activeDevices", activeDevices);
        
        return statistics;
    }
    
    /**
     * 查询区域管理
     * 
     * @param id 区域管理主键
     * @return 区域管理
     */
    @Override
    public Region selectRegionById(Long id)
    {
        return regionMapper.selectRegionById(id);
    }

    /**
     * 查询区域管理列表
     * 
     * @param region 区域管理
     * @return 区域管理
     */
    @Override
    public List<Region> selectRegionList(Region region)
    {
        return regionMapper.selectRegionList(region);
    }

    /**
     * 新增区域管理
     * 
     * @param region 区域管理
     * @return 结果
     */
    @Override
    public int insertRegion(Region region)
    {
        region.setCreateTime(DateUtils.getNowDate());
        return regionMapper.insertRegion(region);
    }

    /**
     * 修改区域管理
     * 
     * @param region 区域管理
     * @return 结果
     */
    @Transactional
    @Override
    public int updateRegion(Region region)
    {
        region.setUpdateTime(DateUtils.getNowDate());
        int result = regionMapper.updateRegion(region);
        empMapper.updateByRegionId(region.getId(), region.getRegionName());
        return result;
    }

    /**
     * 批量删除区域管理
     * 
     * @param ids 需要删除的区域管理主键
     * @return 结果
     */
    @Override
    public int deleteRegionByIds(Long[] ids)
    {
        return regionMapper.deleteRegionByIds(ids);
    }

    /**
     * 删除区域管理信息
     * 
     * @param id 区域管理主键
     * @return 结果
     */
    @Override
    public int deleteRegionById(Long id)
    {
        return regionMapper.deleteRegionById(id);
    }

    @Override
    public List<RegionVo> selectRegionVoList(Region region) {
        return regionMapper.selectRegionVoList(region);
    }
    
    /**
     * 构建前端所需要树结构
     * 
     * @param regions 区域列表
     * @return 树结构列表
     */
    @Override
    public List<Region> buildRegionTree(List<Region> regions) {
        List<Region> returnList = new ArrayList<>();
        List<Long> tempList = new ArrayList<>();
        for (Region dept : regions) {
            tempList.add(dept.getId());
        }
        for (Iterator<Region> iterator = regions.iterator(); iterator.hasNext();) {
            Region region = (Region) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(region.getParentId())) {
                recursionFn(regions, region);
                returnList.add(region);
            }
        }
        if (returnList.isEmpty()) {
            returnList = regions;
        }
        return returnList;
    }
    
    /**
     * 递归列表
     */
    private void recursionFn(List<Region> list, Region t) {
        // 得到子节点列表
        List<Region> childList = getChildList(list, t);
        t.setChildren(childList);
        for (Region tChild : childList) {
            if (hasChild(list, tChild)) {
                // 判断是否有子节点
                Iterator<Region> it = childList.iterator();
                while (it.hasNext()) {
                    Region n = (Region) it.next();
                    recursionFn(list, n);
                }
            }
        }
    }
    
    /**
     * 得到子节点列表
     */
    private List<Region> getChildList(List<Region> list, Region t) {
        List<Region> tlist = new ArrayList<>();
        Iterator<Region> it = list.iterator();
        while (it.hasNext()) {
            Region n = (Region) it.next();
            if (Objects.equals(n.getParentId(), t.getId())) {
                tlist.add(n);
            }
        }
        return tlist;
    }
    
    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<Region> list, Region t) {
        return getChildList(list, t).size() > 0;
    }
    
    /**
     * 构建前端所需要下拉树结构
     * 
     * @param regions 区域列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildRegionTreeSelect(List<Region> regions) {
        List<Region> regionTrees = buildRegionTree(regions);
        return regionTrees.stream().map(this::buildTreeSelect).collect(Collectors.toList());
    }
    
    /**
     * 对象转树
     */
    private TreeSelect buildTreeSelect(Region region) {
        TreeSelect treeSelect = new TreeSelect();
        treeSelect.setId(region.getId());
        treeSelect.setLabel(region.getRegionName());
        if (region.getChildren() != null && !region.getChildren().isEmpty()) {
            List<TreeSelect> childrenSelect = new ArrayList<>();
            for (Region child : region.getChildren()) {
                childrenSelect.add(buildTreeSelect(child));
            }
            treeSelect.setChildren(childrenSelect);
        }
        return treeSelect;
    }
    
    /**
     * 获取区域统计信息
     * 
     * @param regionId 区域ID
     * @return 统计信息（节点数量、员工数量）
     */
    @Override
    public Map<String, Integer> getRegionStatistics(Long regionId) {
        Map<String, Integer> statistics = new HashMap<>();
        // 获取区域下节点数量
        Integer nodeCount = regionMapper.selectNodeCountByRegionId(regionId);
        // 获取区域下员工数量
        Integer employeeCount = regionMapper.selectEmployeeCountByRegionId(regionId);
        
        statistics.put("nodeCount", nodeCount != null ? nodeCount : 0);
        statistics.put("employeeCount", employeeCount != null ? employeeCount : 0);
        
        return statistics;
    }
    
    /**
     * 检查区域层级是否超过限制
     * 
     * @param regionId 区域ID
     * @param maxLevel 最大允许层级
     * @return 是否超过限制
     */
    @Override
    public boolean checkRegionLevelExceeded(Long regionId, int maxLevel) {
        if (regionId == null) {
            return false;
        }
        
        int currentLevel = 0;
        Region region = selectRegionById(regionId);
        
        // 递归查询父区域，计算层级
        while (region != null && region.getParentId() != null && region.getParentId() > 0) {
            currentLevel++;
            // 如果当前层级已经超过最大允许层级，直接返回true
            if (currentLevel >= maxLevel) {
                return true;
            }
            region = selectRegionById(region.getParentId());
        }
        
        // 加上当前节点自身的层级
        currentLevel++;
        return currentLevel > maxLevel;
    }
}
